package com.h2.ref.server.util.portal.handler;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.util.UrlPathHelper;


public class UrlProcessingUrlHandlerMappingWrapper 
      implements HandlerMapping {
   
   private List<String> _processUrls;
   
   private List<String> _excludeUrls;

   private PathMatcher _pathMatcher = new AntPathMatcher();
   
   private UrlPathHelper _urlPathHelper = new UrlPathHelper();
   
   private HandlerMapping _delegate;
   
   
   ////
   ////
   
   public HandlerMapping getDelegate() {
      return _delegate;
   }

   public void setDelegate(HandlerMapping delegate) {
      _delegate = delegate;
   }

   @Override
   public HandlerExecutionChain getHandler(HttpServletRequest request)
         throws Exception {
      if(requiresFilter(request)) {
         return getDelegate().getHandler(request);
      }
      return null;
   }
   
   ////
   ////
   
   protected boolean requiresFilter(HttpServletRequest request) {
      String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
      if(getExcludeUrls() != null) {
         for (String url : getExcludeUrls()) {
            if(getPathMatcher().match(url, lookupPath)) {
               return false;
            }
         }
      }
      if(getProcessUrls() != null) {
         for (String url : getProcessUrls()) {
            if(getPathMatcher().match(url, lookupPath)) {
               return true;
            }
         }
      }
      return false;
   }
   
   /**
    * @return the pathMatcher
    */
   public PathMatcher getPathMatcher() {
      return _pathMatcher;
   }

   /**
    * @param pathMatcher the pathMatcher to set
    */
   public void setPathMatcher(PathMatcher pathMatcher) {
      _pathMatcher = pathMatcher;
   }

   /**
    * @return the urlPathHelper
    */
   public UrlPathHelper getUrlPathHelper() {
      return _urlPathHelper;
   }

   /**
    * @param urlPathHelper the urlPathHelper to set
    */
   public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
      _urlPathHelper = urlPathHelper;
   }
   
   public List<String> getProcessUrls() {
      return _processUrls;
   }

   public void setProcessUrls(List<String> processUrls) {
      _processUrls = processUrls;
   }

   public List<String> getExcludeUrls() {
      return _excludeUrls;
   }

   public void setExcludeUrls(List<String> excludeUrls) {
      _excludeUrls = excludeUrls;
   }

}
